<template>
	<view class="cc-slide-panel-wrap">
		<!-- 遮罩层 -->
		<view v-show="maskvisible" class="cc-slide-panel-mask" @click="handleMaskClick"></view>

		<!-- 弹窗主体 -->
		<view v-show="visible" class="cc-slide-panel" :style="{ transform: `translateY(${translateY})` }">
			<view :style="popupContentStyle" class="cc-slide-panel-content">
				<slot></slot>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'cc-slide-panel',
		props: {
			// 面板最大高度（占屏幕百分比）
			maxHeight: {
				type: Number,
				default: 200
			},
			// 显示/隐藏
			visible: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				translateY: 0, // 动画位移值
				popupContentStyle: {}, // popup的动态高度
				maskvisible: this.visible,
			};
		},
		watch: {
			visible(newVal) {
				if (newVal) {
					this.animateOpen();
				} else {
					this.animateClose();
				}
			}
		},
		methods: {
			// 点击遮罩关闭
			handleMaskClick() {
				this.animateClose();
			},

			// 打开动画
			animateOpen() {
				this.$nextTick(() => {
					this._setHeight();
					this.maskvisible = true;
					this.translateY = 0;
				});
			},

			// 关闭动画
			animateClose() {
				this.translateY = '100%';
				this.maskvisible = false;
				// 动画时长需与CSS一致
				setTimeout(() => {
					this.$emit('update:visible', false);
				}, 100);
			},

			// 动态计算内容高度
			_setHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.cc-slide-panel-content').boundingClientRect(res => {
					const contentHeight = res.height;
					const maxHeight = parseFloat(this.maxHeight);
					this.popupContentStyle = {
						maxHeight: `${Math.min(contentHeight, maxHeight)}px`
					}
				}).exec();
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/cc-ui-tools/scss/animation.scss";

	.cc-slide-panel-mask {
		position: absolute;
		left: 0;
		right: 0;
		height: 100%;
		bottom: 100rpx;
		background: rgba(0, 0, 0, 0.5);
		z-index: 9999;
		animation: fadeIn 0.2s linear both;
	}

	.cc-slide-panel {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 100rpx;
		background: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		transition: transform 0.1s ease-out;
		z-index: 9999;
	}

	.cc-slide-panel-content {
		padding-top: 20rpx;
		overflow-y: auto;
		/* iOS 滚动优化 */
		-webkit-overflow-scrolling: touch;

		/* 动态高度计算 */
		/* 默认最大高度 */
		max-height: 70vh;
	}
</style>